<template>
  <q-scroll-area class="timeline full-height" :thumb-style="thumbStyle">
    <div class="flex justify-center padding-20" style="position: relative">
      <div class="flex items-center">
        <q-btn round color="primary" size="6px" icon="chevron_left" style="margin: 0 10px" :disable="!fromList"
               @click="prevDate()" />
        <date-picker v-model="selDate" valueType="format" placeholder="选择日期" :disabled="!fromList" :clearable="false" :editable="false"></date-picker>
        <q-btn round color="primary" size="6px" icon="chevron_right" style="margin: 0 10px" :disable="!fromList"
               @click="nextDate()" />
        <q-btn color="primary" label="返回今天" @click="returnToday"
               :disable="selDate == $utils.formatDate(new Date()) || !fromList" />
      </div>
      <q-toggle v-model="showScale"
                label="启用缩放"
                left-label
                @input="scale"
                style="position: absolute; right: 20px; height: 30px"
      />
    </div>
    <div class="legend flex justify-end full-width" style="padding: 20px 20px 0"  ref="charts">
      <div v-for="(item, index) in allStatusList" :key="index" class="flex padding-l-20">
        <div :style="{backgroundColor: item.color}" style="border-radius: 50%;height: 10px;width: 10px;margin: 5px 5px 5px 0"></div>
        <div>{{item.label}}</div>
      </div>
    </div>
    <!-- 班次 -->
    <div v-for="i in 4" :key="i" v-show="scheduling[i - 1]"
         class="flex margin-t-20 rounded-borders margin-l-20 margin-r-20 text-white overflow-hidden"
         style="border: 1px solid #d3d3d3;height: 292px">
      <div class="card-title text-center font-size-16 flex items-center"
           style="background-color: #5F77FD">
        {{ scheduling[i - 1] ? scheduling[i - 1].name : '' }}
      </div>
      <!-- 图表 -->
      <div style="width: calc(100% - 48px); display: block;">
        <div class="chart full-width" style="height: 174px" />
        <div
          class="q-table__container q-table--horizontal-separator q-table--cell-separator q-table__card q-table--no-wrap scroll scroll-table myTable full-width"
          style="margin: 0px; padding: 0 20px 20px">
          <div class="q-table__middle scroll">
            <table class="q-table">
              <thead>
                <tr>
                  <th class="text-left" v-for="(item, index) in allStatusList" :key="index">
                    {{item.label}}
                  </th>
                </tr>
              </thead>
              <tbody>
                <td class="text-left"
                    style="border-bottom: 0"
                    :style="{borderRightWidth: index === allStatusList.length - 1 ? 0 : 1}"
                    v-for="(item, index) in allStatusList" :key="index">
                  {{scheduling[i - 1] ? (chartsTime ? chartsTime[i - 1][item.key]: '0秒') : ''}}
                </td>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div v-if="scheduling.length === 0 && isGetAxios" class="full-width flex justify-center items-center column" style="height: 450px">
      <img src="../../statics/img/no-time.png" alt="">
      <div style="color: #999">今天是休息日哦</div>
    </div>
    <div class="flex margin-t-20 rounded-borders margin-l-20 margin-r-20 text-white overflow-hidden"
         style="border: 1px solid #d3d3d3;height: 260px" v-if="productList.length > 0">
      <div class="card-title text-center font-size-16 flex items-center"
           style="background-color: #44D8C6">循环统计
      </div>
      <div class="product-list flex overflow-hidden text-black" v-if="productList.length <= 3">
        <div class="product-item rounded-borders" v-for="(item,index) in productList" :key="index" :style="{width: `calc(100% / ${productList.length} - 20px)`}">
          <div class="text-ellipsis title text-center font-size-16">
            {{item.productName || '--'}}
            <span  v-if="item.productName !== '无'" >-{{item.processName || '--'}}</span>
            <q-tooltip>{{item.productName || '--'}} <span  v-if="item.productName !== '无'">-{{item.processName || '--'}}</span> </q-tooltip>
          </div>
          <div class="font-16 text-grey margin-t-20" style="line-height: 1">
            *CT(理论循环时间)：{{getProcessTime(item.processTime)}}
            <span>
              <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
              <q-tooltip max-width="300px">值为此产品工序的预计加工工时</q-tooltip>
            </span>
          </div>
          <div class=" flex text-center" style="height: calc(100% - 95px)">
            <div style="flex:1;padding-top: 50px">
              <div class="margin-b-10">总循环</div>
              <div style="font-size: 24px">{{item.count}}次循环</div>
            </div>
            <div style="flex:1;padding-top: 50px">
              <div class="margin-b-10">平均循环时间</div>
              <div style="font-size: 24px">{{getDuration(item.averageDuration)}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="product-list text-black" style="padding: 0" v-else>
        <swiper :options="swiperOption" style="height: inherit;padding: 0 20px">
          <swiper-slide v-for="(item,index) in productList" :key="index">
            <div class="product-item rounded-borders">
              <div class="text-ellipsis title text-center font-size-16">
                {{item.productName || '--'}}
                <span  v-if="item.productName !== '无'" >({{item.processName || '--'}})</span>
                <q-tooltip>{{item.productName || '--'}} <span  v-if="item.productName !== '无'">-{{item.processName || '--'}}</span> </q-tooltip>
              </div>
              <div class="font-16 text-grey margin-t-20" style="line-height: 1">
                *CT(理论循环时间)：{{getProcessTime(item.processTime)}}
                <span>
                  <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
                  <q-tooltip max-width="300px">值为此产品工序的预计加工工时</q-tooltip>
                </span>
              </div>
              <div class=" flex text-center" style="height: calc(100% - 95px)">
                <div style="flex:1;padding-top: 50px">
                  <div class="margin-b-10">总循环</div>
                  <div style="font-size: 24px">{{item.count}}次循环</div>
                </div>
                <div style="flex:1;padding-top: 50px">
                  <div class="margin-b-10">平均循环时间</div>
                  <div style="font-size: 24px">{{getDuration(item.averageDuration)}}</div>
                </div>
              </div>
            </div>
          </swiper-slide>
          <div class="swiper-button-prev" slot="button-prev">
            <q-btn round color="primary" size="13px" icon="chevron_left" style="margin: 0" />
          </div>
          <div class="swiper-button-next" slot="button-next">
            <q-btn round color="primary" size="13px" icon="chevron_right" style="margin: 0" />
          </div>
        </swiper>
      </div>
    </div>
    <div class="flex justify-between padding-20 margin-t-20 " style="padding-bottom: 10px">
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['normal-cycle'].id,name:CommonConfig.statData.machine['normal-cycle'].name}"
           @click="showNormalDetail">
        <q-icon class="iconfont icontubiao-123" style="font-size: 48px;color: #44d8c6" />
        <div class="font-size-16">正常循环明细</div>
        <div class="font-size-16 margin-t-10">(共{{normalList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['downtime-detail'].id,name:CommonConfig.statData.machine['downtime-detail'].name}"
           @click="showDowntimeDurationDetail">
        <q-icon class="iconfont icontubiao-121" style="font-size: 48px;color: #ff8559" />
        <div class="font-size-16">{{ statusList[1].label }}时间明细</div>
        <div class="font-size-16 margin-t-10">(共{{downtimeList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center margin-r-20"
           v-stat="{id:CommonConfig.statData.machine['warning-detail'].id,name:CommonConfig.statData.machine['warning-detail'].name}"
           @click="showWarningDetail">
        <q-icon class="iconfont icontubiao-78" style="font-size: 48px;color: #e43434" />
        <div class="font-size-16">{{ statusList[4].label }}明细</div>
        <div class="font-size-16 margin-t-10">(共{{warningList}}次)</div>
      </div>
      <div class="detail-item flex items-center column justify-center"
           v-stat="{id:CommonConfig.statData.machine['close-detail'].id,name:CommonConfig.statData.machine['close-detail'].name}"
           @click="showCloseDetail">
        <q-icon class="iconfont icontubiao-144" style="font-size: 48px;color: #666" />
        <div class="font-size-16">{{ statusList[3].label }}明细</div>
        <div class="font-size-16 margin-t-10">(共{{offlineList}}次)</div>
      </div>
<!--      <div class="detail-item flex items-center column justify-center"-->
<!--           v-stat="{id:CommonConfig.statData.machine['abnormal-list'].id,name:CommonConfig.statData.machine['abnormal-list'].name}"-->
<!--           @click="showAbnormalDetail">-->
<!--        <q-icon class="iconfont icontubiao-113" style="font-size: 48px;color: #f7b82d" />-->
<!--        <div class="font-size-16">异常循环明细</div>-->
<!--        <div class="font-size-16 margin-t-10">(共{{abnormalList}}次)</div>-->
<!--      </div>-->
    </div>
    <!-- 正常循环明细 -->
    <normal-cycle
      :show="normal.show"
      :since="since"
      :before="before"
      :deviceId="params.id"
      @close="normal.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 停机时长明细 -->
    <downtime-duration-detail
      :show="downtimeDuration.show"
      :since="since"
      :before="before"
      :deviceId="params.id"
      :scheduling="scheduling"
      @close="downtimeDuration.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 报警明细 -->
    <warning-detail
      :show="warning.show"
      :since="since"
      :before="before"
      :deviceId="params.id"
      @close="warning.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 离线明细 -->
    <close-detail
      :show="closeDetail.show"
      :since="since"
      :before="before"
      :deviceId="params.id"
      @close="closeDetail.show = false"
      @getDetailedCount="getDetailedCount()"
    />
    <!-- 异常明细 -->
    <abnormal-detail
      :show="abnormalDetail.show"
      :since="since"
      :before="before"
      :deviceId="params.id"
      @close="abnormalDetail.show = false"
      @initData="initData()"
      @getDetailedCount="getDetailedCount()"
    />
  </q-scroll-area>
</template>

<script>
import normalCycle from './components/normal-cycle'
import downtimeDurationDetail from './components/stop-time-dialog'
import warningDetail from './components/warning-detail'
import closeDetail from './components/close-detail'
import abnormalDetail from './components/abnormal-detail'
import { MachineStatsChart } from './machine-stats-chart'
import { date } from 'quasar'
import _, { cloneDeep } from 'lodash'
import {
  getMachineTimelineData,
  getStartDateTime, getProductList, getDetailedCount
} from '../../boot/status-monitor/machine'
import { addListener } from 'resize-detector'
import transformTime from './components/transform-time'
import echarts from 'echarts'
import { mapGetters } from 'vuex'
import roleMenuApi from '../../boot/system/role-menu'

export default {
  name: 'time-line',
  props: {
    msg: {
      type: String,
      default: ''
    },
    details: {
      type: Object
    },
    fromList: {
      type: Boolean,
      default: false
    },
    change: null
  },
  components: {
    normalCycle,
    downtimeDurationDetail,
    warningDetail,
    closeDetail,
    abnormalDetail
  },
  created () {
    this.params = this.details
    if (!this.fromList) {
      this.selDate = this.details.date
    }
  },
  computed: {
    ...mapGetters([
      'statusList',
      'userInfo'
    ])
  },
  watch: {
    details (val) {
      if (val) {
        this.params = this.details
        // console.log(this.params.boxId, 'change时间线')
        this.getStartDateTime()
      }
    },
    selDate (val) {
      if (val && this.details.boxId && this.details.id) {
        this.getStartDateTime()
      }
      // this.renderCharts()
    }
  },
  mounted () {
    if (!this.details.date) {
      this.selDate = this.$utils.formatDate(new Date())
    }
    this.nowDate = this.$utils.formatDate(new Date())
    this.hasCraftMenu().then(() => {
      this.initStatusData()
      this.initCharts()
    })
    // window.addEventListener('resize', () => {
    //   this.charts.forEach(o => o.resize().rerender())
    // })
    addListener(this.$refs.charts, this.$utils.debounce(() => {
      if (this.charts.length) {
        this.charts.forEach(o => o.resize().rerender())
      }
    }, 100))

    // this.getStartDateTime()
  },
  data () {
    return {
      isGetAxios: false,
      params: {}, // 状态页卡片传参
      since: null, // 当天班制开始时间
      before: null, // 当天班制结束时间
      normalList: 0, // 正常循环数量
      downtimeList: 0, // 停机循环数量
      warningList: 0, // 报警循环数量
      abnormalList: 0, // 异常明细数量
      offlineList: 0, // 离线数量
      scheduling: [],
      // 表格列
      tableColumns: [],
      charts: [],
      selDate: '',
      showScale: false, // 是否可以缩放
      // 停机时长明细
      downtimeDuration: {
        show: false
      },
      // 正常明细
      normal: {
        show: false
      },
      // 报警明细
      warning: {
        selected: [],
        show: false
      },
      // 报警明细
      closeDetail: {
        selected: [],
        show: false
      },
      // 异常明细
      abnormalDetail: {
        selected: [],
        show: false
      },
      chartsTime: [{}, {}, {}, {}],
      allStatusList: [], // 状态列表
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      productList: [],
      hasCraft: false, // 生产模块权限
      hasWork: false, // 维保模块权限
      swiperOption: {
        slidesPerView: 3,
        spaceBetween: 20,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev'
        }
      }
    }
  },
  methods: {
    hasCraftMenu () {
      // 从状态中获取租户Id
      const tenantId = this.userInfo.tenant_id
      // 获取租户所购买的所有系统视图
      return roleMenuApi.getCompanyView(tenantId, 'pc').then(res => {
        this.hasCraft = _.indexOf(res.data, this.Enums.SYS_PERMISSION.CRAFT_MENU.value) !== -1
        this.hasWork = _.indexOf(res.data, this.Enums.SYS_PERMISSION.WORK_MENU.value) !== -1
      })
    },
    // 获取CT
    getProcessTime (data) {
      return _.isNil(data) ? '未派工单' : this.getDuration(data)
    },
    changeData (details) {
      this.selDate = details.date
      this.params = details
    },
    getTime (index, key) {
      console.log(this.chartsTime[index], index, key)
      return _.isEmpty(this.chartsTime[index]) ? '0秒' : this.chartsTime[index][key]
    },
    scale () {
      this.charts.map(v => {
        v._changeZoom(!this.showScale).rerender()
      })
    },
    /**
       * 初始化图表
       */
    initCharts () {
      document.querySelectorAll('.chart').forEach(el => {
        this.charts.push(new MachineStatsChart(echarts.init(el), this.allStatusList))
      })
    },
    initStatusData () {
      let tableColumns = [
        { name: 'id', field: 'id', label: '', align: 'left' }
      ]
      let newArr = Object.entries(this.Enums.MACHINES_STATUS)
      const cloneNewArr = cloneDeep(newArr)
      if (!this.hasCraft && this.hasWork) {
        cloneNewArr.splice(5, 1)
      } else if (!this.hasWork && this.hasCraft) {
        cloneNewArr.splice(6, 2)
      } else if (!this.hasCraft && !this.hasWork) {
        cloneNewArr.splice(5, 3)
      }
      const statusList = _.union(_.cloneDeep(this.statusList), cloneNewArr.slice(5, cloneNewArr.length))
        .map((entry, i) => {
          const key = i < 5 ? entry.key : entry[0]
          const label = i < 5 ? entry.label : entry[1].desc
          tableColumns.push(
            { name: (key + '').toLowerCase(), field: (key + '').toLowerCase(), label: label, align: 'left' }
          )
          return {
            value: i < 5 ? entry.value : entry[1].value,
            label: label,
            color: i < 5 ? entry.color : entry[1].color,
            key: (key + '').toLowerCase()
          }
        })
      this.tableColumns = tableColumns
      this.allStatusList = statusList
    },
    initData () {
      this.renderCharts()
      this.getProductList()
      this.getDetailedCount()
    },
    // 获取当天班制开始结束时间
    getStartDateTime () {
      this.isGetAxios = false
      getStartDateTime(this.params.boxId, this.params.id, this.selDate).then(res => {
        if (res.data && res.data.since && res.data.before) {
          this.since = res.data.since
          this.before = res.data.before
          this.initData()
        } else {
          this.isGetAxios = true
          // 无班制时置空数据
          this.productList = []
          this.scheduling = []
          this.since = null
          this.before = null
          this.normalList = 0
          this.downtimeList = 0
          this.warningList = 0
          this.abnormalList = 0
          this.offlineList = 0
          this.$message.warning('当天无有效班制')
        }
      })
    },
    // 获取产品循环统计
    getProductList () {
      getProductList(this.params.id, this.since, this.before).then(res => {
        res.data.forEach(o => {
          if (o.productName === '-' || o.productName === '--') {
            o.productName = '无'
          }
        })
        this.productList = res.data
      })
    },
    // 转换时长
    getDuration (second) {
      return transformTime.getDuration(second)
    },
    // 获取明细数量
    getDetailedCount () {
      getDetailedCount(this.params.id, this.since, this.before).then(res => {
        this.normalList = res.data.normalWorkpiece
        this.downtimeList = res.data.stop
        this.warningList = res.data.alarm
        this.offlineList = res.data.offline
        this.abnormalList = res.data.abnormalWorkpiece
      })
    },
    /**
       * 渲染数据到图表
       */
    async renderCharts () {
      this.charts.forEach(chart => chart.getInstance().showLoading())

      await this.getMachineStats()

      const chartsTime = [{}, {}, {}, {}]
      this.scheduling.forEach((aScheduling, i) => {
        this.charts[i]
          .setSchedulingTime(new Date(aScheduling.from), new Date(aScheduling.to))
          .setData({
            rests: aScheduling.rests,
            stats: aScheduling.events
          })
          .rerender()
        this.allStatusList.forEach(item => {
          chartsTime[i][item.key] = this.charts[i].getStatTotalDurations(item.key)
        })
      })

      this.chartsTime = chartsTime
      this.charts.forEach(chart => chart.getInstance().hideLoading())

      if (this.charts.length) {
        this.charts.forEach(o => o.resize().rerender())
      }
    },
    getMachineStats () {
      return getMachineTimelineData(this.params.boxId, this.params.id, this.selDate)
        .then(res => {
          this.scheduling = res.data.shifts
        })
    },
    // 下一天
    nextDate () {
      this.selDate = this.$utils.formatDate(date.addToDate(this.selDate, { days: 1 }))
      // this.getStartDateTime()
    },
    // 上一天
    prevDate () {
      this.selDate = this.$utils.formatDate(date.subtractFromDate(this.selDate, { days: 1 }))
      // this.getStartDateTime()
    },
    // 返回今日
    returnToday () {
      this.selDate = this.$utils.formatDate(new Date())
      // this.getStartDateTime()
    },
    showNormalDetail () {
      this.normal.show = true
    },
    showWarningDetail () {
      this.warning.show = true
    },
    showCloseDetail () {
      this.closeDetail.show = true
    },
    showDowntimeDurationDetail () {
      this.downtimeDuration.show = true
    },
    showAbnormalDetail () {
      this.abnormalDetail.show = true
    }
  }
}
</script>

<style scoped lang="stylus">
  .padding-20 {
    padding 0 20px
  }

  .detail-item {
    flex 1
    cursor pointer
    height 175px
    box-shadow 0px 1px 7px 0px rgba(0, 0, 0, 0.15)
    border-radius 6px
    overflow hidden
    &:hover{
      background-color #e8ebff
      transition all 500ms ease-in-out
    }
  }

  .card-title {
    width 48px
    height inherit
    padding 0 16px
    word-break: break-all
  }

  .product-list {
    height inherit
    width calc(100% - 48px)
    padding 0 20px
  }

  .product-item {
    box-shadow 0px 1px 7px 0px rgba(0, 0, 0, 0.15)
    height inherit
    flex 1
    margin-right 20px
    padding 0 10px

    .title {
      line-height 56px
      border-bottom $border
    }
  }

  .product-item:last-child {
    margin 0
  }

  .swiper-button-prev, .swiper-button-next {
    background-image none
    width 39px
    height 39px
  }

</style>
